<template>
  <div class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-10">
    <div class="bg-white rounded-lg shadow-xl w-full max-w-2xl p-6">
      <div class="flex justify-between items-center mb-4">
        <h3 class="text-lg font-medium">搜索聊天记录</h3>
        <button @click="$emit('close')" class="text-gray-400 hover:text-gray-500">
          &times;
        </button>
      </div>
      
      <!-- 搜索框 -->
      <div class="mb-4">
        <label for="search-keyword" class="sr-only">搜索关键词</label>
        <div class="relative">
          <input 
            id="search-keyword"
            v-model="keyword" 
            @keydown.enter="handleSearch"
            type="text" 
            placeholder="输入关键词搜索消息内容（至少2个字符）" 
            class="form-input w-full pl-8 py-2 search-input"
          />
          <span class="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400">
            🔍
          </span>
          <!-- 清空按钮 -->
          <button 
            v-if="keyword.trim()"
            @click="clearSearch"
            class="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600"
            title="清空搜索"
          >
            ✕
          </button>
        </div>
      </div>
      
      <!-- 搜索历史 -->
      <div v-if="showSearchHistory && searchHistory.length > 0" class="mb-4 bg-gray-50 rounded-lg p-3">
        <div class="flex items-center justify-between mb-2">
          <h4 class="text-sm font-medium text-gray-700">搜索历史</h4>
          <button 
            @click="clearSearchHistory"
            class="text-xs text-gray-500 hover:text-red-600 transition-colors"
          >
            清空历史
          </button>
        </div>
        <div class="flex flex-wrap gap-2">
          <button
            v-for="historyItem in searchHistory"
            :key="historyItem"
            @click="useHistoryKeyword(historyItem)"
            class="px-2 py-1 text-xs bg-white border border-gray-200 rounded-md hover:bg-blue-50 hover:border-blue-300 transition-colors"
          >
            {{ historyItem }}
          </button>
        </div>
      </div>
      
      <!-- 搜索状态和结果统计 -->
      <div v-if="keyword.trim().length >= 2 && !loading" class="mb-2 text-sm text-gray-600">
        <span v-if="searchResults.length > 0">
          找到 {{ searchResults.length }} 条相关消息
        </span>
        <span v-else-if="!error">
          未找到包含 "{{ keyword }}" 的消息
        </span>
      </div>
      
      <!-- 搜索结果 -->
      <div v-if="loading" class="py-10 text-center text-gray-500">
        <div class="animate-spin inline-block w-6 h-6 border-[3px] border-current border-t-transparent text-blue-600 rounded-full mb-2" role="status" aria-label="loading">
        </div>
        <div>正在搜索...</div>
      </div>
      <div v-else-if="error" class="py-10 text-center text-red-500">
        <div class="text-4xl mb-2">⚠️</div>
        <div>{{ error }}</div>
        <button @click="performSearch(true)" class="mt-2 text-sm text-blue-600 hover:text-blue-700 underline">
          重试
        </button>
      </div>
      <div v-else-if="searchResults.length === 0 && keyword.trim().length >= 2" class="py-10 text-center text-gray-500">
        <div class="text-4xl mb-2">🔍</div>
        <div>未找到包含 "{{ keyword }}" 的消息</div>
        <div class="text-xs text-gray-400 mt-1">尝试使用其他关键词</div>
      </div>
      <div v-else-if="keyword.trim().length > 0 && keyword.trim().length < 2" class="py-10 text-center text-gray-500">
        <div class="text-4xl mb-2">✏️</div>
        <div>请输入至少2个字符开始搜索</div>
      </div>
      <div v-else-if="keyword.trim().length === 0" class="py-10 text-center text-gray-400">
        <div class="text-4xl mb-2">💬</div>
        <div>输入关键词搜索聊天记录</div>
        <div class="text-xs mt-1">支持搜索消息内容</div>
      </div>
      <div v-else-if="searchResults.length > 0" class="max-h-96 overflow-y-auto">
        <div 
          v-for="message in searchResults" 
          :key="message._id"
          class="p-4 border-b border-gray-200 last:border-0 hover:bg-blue-50 cursor-pointer transition-colors duration-150 rounded-lg mb-2 bg-white shadow-sm search-result-item"
          @click="handleMessageClick(message)"
        >
          <div class="flex items-start">
            <UserAvatar 
              :username="message.sender.username"
              :avatar="message.sender.avatar"
              :userId="message.sender._id"
              size="sm"
              :clickable="true"
              class="mr-3 flex-shrink-0"
            />
            <div class="flex-1 min-w-0">
              <div class="flex items-center justify-between mb-1">
                <span class="font-medium text-gray-900 truncate">{{ message.sender.username }}</span>
                <span class="text-xs text-gray-500 flex-shrink-0 ml-2">{{ formatTime(message.createdAt) }}</span>
              </div>
              <div class="text-sm">
                <div v-html="highlightKeyword(message.content)" class="text-gray-700 leading-relaxed break-words"></div>
              </div>
              <!-- 消息类型标识 -->
              <div v-if="message.receiver && message.receiver._id.startsWith('group_')" class="mt-1">
                <span class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-blue-100 text-blue-800">
                  👥 群聊消息
                </span>
              </div>
              <div v-else class="mt-1">
                <span class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-green-100 text-green-800">
                  👤 私聊消息
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 底部按钮 -->
      <div class="mt-4 flex justify-end">
        <button 
          @click="$emit('close')" 
          class="px-4 py-2 bg-gray-200 text-gray-700 rounded-md hover:bg-gray-300"
        >
          关闭
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue';
import { useChatStore } from '@/stores/chat';
import { useAuthStore } from '@/stores/auth';
import UserAvatar from '@/components/UserAvatar.vue';

// 获取store
const chatStore = useChatStore();
const authStore = useAuthStore();

const props = defineProps({
  userId: {
    type: String,
    required: true
  }
});

const emit = defineEmits(['close', 'select-message']);

// 搜索相关
const keyword = ref('');
const searchResults = ref<any[]>([]);
const loading = ref(false);
const error = ref('');
const searchTimeout = ref<number | null>(null);
const lastSearchKeyword = ref(''); // 记录上次搜索的关键词，避免重复搜索
const searchHistory = ref<string[]>([]); // 搜索历史
const showSearchHistory = ref(false); // 是否显示搜索历史

// 从localStorage加载搜索历史
function loadSearchHistory() {
  try {
    const saved = localStorage.getItem(`search_history_${props.userId}`);
    if (saved) {
      searchHistory.value = JSON.parse(saved).slice(0, 10); // 最多保存10条历史
    }
  } catch (e) {
    console.error('加载搜索历史失败:', e);
  }
}

// 保存搜索历史到localStorage
function saveSearchHistory(searchTerm: string) {
  try {
    const trimmed = searchTerm.trim();
    if (trimmed.length < 2) return;
    
    // 移除重复项并添加到开头
    searchHistory.value = [trimmed, ...searchHistory.value.filter(h => h !== trimmed)].slice(0, 10);
    localStorage.setItem(`search_history_${props.userId}`, JSON.stringify(searchHistory.value));
  } catch (e) {
    console.error('保存搜索历史失败:', e);
  }
}

// 使用历史搜索词
function useHistoryKeyword(historyKeyword: string) {
  keyword.value = historyKeyword;
  showSearchHistory.value = false;
  performSearch(true);
}

// 清空搜索历史
function clearSearchHistory() {
  searchHistory.value = [];
  localStorage.removeItem(`search_history_${props.userId}`);
}

// 使用watch而不是watchEffect，只监听keyword的变化
watch(keyword, (newValue) => {
  // 清除之前的定时器
  if (searchTimeout.value) {
    clearTimeout(searchTimeout.value);
    searchTimeout.value = null;
  }
  
  // 控制搜索历史显示
  showSearchHistory.value = newValue.trim().length === 0 && searchHistory.value.length > 0;
  
  // 如果输入为空，清空结果
  if (!newValue.trim()) {
    searchResults.value = [];
    error.value = '';
    return;
  }
  
  // 输入长度不足，不搜索
  if (newValue.trim().length < 2) {
    error.value = '请输入至少2个字符';
    searchResults.value = [];
    return;
  }
  
  // 已经搜索过相同关键词，不重复搜索
  if (newValue.trim() === lastSearchKeyword.value && searchResults.value.length > 0) {
    return;
  }
  
  // 设置500ms的防抖，避免频繁请求
  searchTimeout.value = setTimeout(() => {
    // 执行搜索
    performSearch();
  }, 500) as unknown as number;
});

// 执行搜索
async function performSearch(immediate = false) {
  // 如果正在加载中，不再触发新的搜索
  if (loading.value) return;
  
  if (!keyword.value.trim()) {
    searchResults.value = [];
    error.value = '';
    return;
  }

  if (keyword.value.length < 2) {
    error.value = '请输入至少2个字符';
    return;
  }
  
  // 如果搜索关键词没有变化，不重复搜索
  if (keyword.value.trim() === lastSearchKeyword.value && searchResults.value.length > 0 && !immediate) {
    return;
  }
  
  // 如果未强制立即搜索，且仍有定时器在运行，不执行搜索
  if (searchTimeout.value && !immediate) {
    return;
  }
  
  // 清除定时器
  if (searchTimeout.value) {
    clearTimeout(searchTimeout.value);
    searchTimeout.value = null;
  }
  
  loading.value = true;
  error.value = '';
  showSearchHistory.value = false; // 搜索时隐藏历史
  
  try {
    // 记录此次搜索的关键词
    lastSearchKeyword.value = keyword.value.trim();
    
    const result = await chatStore.searchMessages(props.userId, keyword.value);
    if (result.success) {
      searchResults.value = result.messages;
      if (searchResults.value.length === 0) {
        error.value = '';
      }
      // 保存搜索历史（仅当有搜索结果时）
      if (searchResults.value.length > 0) {
        saveSearchHistory(keyword.value.trim());
      }
    } else {
      console.error('搜索失败:', result);
      error.value = result.message || '搜索失败，请重试';
    }
  } catch (e) {
    console.error('搜索异常:', e);
    error.value = '搜索失败，请重试';
  } finally {
    loading.value = false;
  }
}

// 处理手动搜索（用户按Enter键）
function handleSearch() {
  // 强制立即搜索
  performSearch(true);
}

// 点击消息
function handleMessageClick(message: any) {
  emit('select-message', message);
  emit('close');
}

// 高亮关键词
function highlightKeyword(text: string) {
  if (!keyword.value.trim()) return text;
  
  try {
    // 分割关键词（支持空格分隔的多个关键词）
    const keywords = keyword.value.trim().split(/\s+/).filter(k => k.length > 0);
    let highlightedText = text;
    
    // 为每个关键词添加高亮
    keywords.forEach((kw, index) => {
      const escapedKeyword = kw.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
      const regex = new RegExp(`(${escapedKeyword})`, 'gi');
      const highlightClass = index % 3 === 0 ? 'bg-yellow-200' : index % 3 === 1 ? 'bg-blue-200' : 'bg-green-200';
      highlightedText = highlightedText.replace(regex, `<span class="${highlightClass} px-1 rounded font-medium">$1</span>`);
    });
    
    return highlightedText;
  } catch (e) {
    console.error('高亮关键词错误:', e);
    return text;
  }
}

// 格式化时间
function formatTime(timestamp: string): string {
  const date = new Date(timestamp);
  const now = new Date();
  const diff = now.getTime() - date.getTime();
  
  // 今天的消息，显示时:分
  if (date.toDateString() === now.toDateString()) {
    return `今天 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
  }
  
  // 昨天的消息
  const yesterday = new Date();
  yesterday.setDate(yesterday.getDate() - 1);
  if (date.toDateString() === yesterday.toDateString()) {
    return `昨天 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
  }
  
  // 一周内的消息
  if (diff < 7 * 24 * 60 * 60 * 1000) {
    const days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
    return `${days[date.getDay()]} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
  }
  
  // 更早的消息
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
}

// 清空搜索
function clearSearch() {
  keyword.value = '';
  searchResults.value = [];
  error.value = '';
  showSearchHistory.value = searchHistory.value.length > 0;
}

// 初始化组件时聚焦搜索框
onMounted(() => {
  const searchInput = document.querySelector('.search-input') as HTMLInputElement;
  if (searchInput) {
    searchInput.focus();
  }
  
  // 加载搜索历史
  loadSearchHistory();
  // 如果没有关键词且有搜索历史，则显示搜索历史
  showSearchHistory.value = keyword.value.trim().length === 0 && searchHistory.value.length > 0;
});
</script>

<style scoped>
.form-input {
  @apply block w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring focus:ring-primary focus:ring-opacity-50;
}

/* 关键词高亮样式 */
:deep(.bg-yellow-200) {
  background-color: #fef08a;
  box-shadow: 0 0 0 1px rgba(251, 191, 36, 0.3);
}

:deep(.bg-blue-200) {
  background-color: #dbeafe;
  box-shadow: 0 0 0 1px rgba(59, 130, 246, 0.3);
}

:deep(.bg-green-200) {
  background-color: #dcfce7;
  box-shadow: 0 0 0 1px rgba(34, 197, 94, 0.3);
}

/* 搜索结果动画 */
.search-result-item {
  animation: fadeInUp 0.3s ease-out;
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 加载动画 */
@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.animate-spin {
  animation: spin 1s linear infinite;
}

/* 搜索框清空按钮样式 */
.search-input:focus + .absolute {
  display: flex;
}
</style> 